package net.lesscoding.handler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.message.HeartBeatMessage;
import net.lesscoding.protocol.ProtocolFrameDecoder;
import net.lesscoding.protocol.SharedMessageCodec;

/**
 * @author eleven
 * @date 2024/10/31 14:50
 * @apiNote
 */
@Data
@AllArgsConstructor
@Slf4j
public class ChatClientChannelInitializer extends ChannelInitializer<SocketChannel> {

    private LoggingHandler loggingHandler;
    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        channel.pipeline()
                .addLast(new ProtocolFrameDecoder())
                //.addLast(loggingHandler)
                .addLast(new SharedMessageCodec())
                .addLast(new IdleStateHandler(0, 3,0))
                .addLast(new ChannelDuplexHandler() {

                  @Override
                  public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                      IdleStateEvent event = (IdleStateEvent) evt;
                      if (event.state() == IdleState.WRITER_IDLE) {
                          log.info("发送心跳包");
                          ctx.writeAndFlush(HeartBeatMessage.INSTANCE);
                      }
                  }
                })
                .addLast("clientHandler", new ClientChannelAdapter())
        ;
    }
}
